/**
 * Main Quiz Application Logic
 * Handles loading questions, game sessions, and progress tracking.
 */

const app = {
    questions: [],
    currentSession: [],
    currentIndex: 0,
    score: { correct: 0, wrong: 0, answered: 0 },
    lastMode: 'new', // new, mistakes, all
    userProgress: {}, // Loaded from server/local

    // Config default
    config: window.APP_CONFIG || {},

    init: async () => {
        // Load User
        app.loadUser();

        // Initialize Edital Sidebar (New)
        app.initEdital();

        // Load Questions
        await app.loadQuestions();

        // Load Progress Stats
        await app.loadProgress();

        // Update Menu Stats
        app.updateMenuStats();

        // Event Listeners
        // (Handled via onclick in HTML or added here if needed)
    },

    loadUser: () => {
        let user = localStorage.getItem('quiz_user');
        if (!user) {
            user = prompt("Por favor, digite seu nome para registrar o progresso:", "Estudante");
            if (!user) user = "Estudante";
            localStorage.setItem('quiz_user', user);
        }
        document.getElementById('user-name-display').textContent = user;
        app.currentUser = user;
    },

    // --- Edital Feature ---
    editalText: '',
    initEdital: async () => {
        // Expose to window immediately for onclick handlers
        window.app = app;

        // 1. Inject Floating Button
        const btn = document.createElement('button');
        btn.innerHTML = '<span class="material-icons" style="font-size: 24px;">menu_book</span>';
        btn.id = 'edital-toggle-btn';
        btn.className = 'fixed bottom-6 right-6 bg-blue-600 hover:bg-blue-700 text-white w-14 h-14 rounded-full shadow-2xl z-50 transition transform hover:scale-110 flex items-center justify-center cursor-pointer';
        btn.style.zIndex = '9999'; // Ensure top level
        btn.title = "Consultar Edital";
        // Use direct event listener instead of HTML onclick for reliability
        btn.onclick = (e) => {
            e.stopPropagation();
            app.toggleEdital();
        };
        document.body.appendChild(btn);

        // 2. Inject Sidebar HTML
        const sidebar = document.createElement('div');
        sidebar.id = 'edital-sidebar';
        sidebar.className = 'shadow-2xl'; // Tailwind shadow
        sidebar.innerHTML = `
            <div class="p-4 border-b border-gray-200 bg-white/95 backdrop-blur flex justify-between items-center sticky top-0 z-20">
                <h3 class="font-bold text-lg text-gray-800 flex items-center gap-2">
                    <span class="material-icons text-blue-600">article</span> Edital
                </h3>
                <button id="edital-close-btn" class="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-full transition cursor-pointer">
                    <span class="material-icons">close</span>
                </button>
            </div>
            <div class="p-4 bg-gray-50 border-b border-gray-200 sticky top-[69px] z-20">
                <div class="relative">
                    <span class="material-icons absolute left-3 top-2.5 text-gray-400 text-sm">search</span>
                    <input type="text" id="edital-search" placeholder="Filtrar tópicos..." 
                        class="w-full pl-9 pr-4 py-2 rounded-lg border border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 outline-none text-sm transition">
                </div>
            </div>
            <div id="edital-content" class="text-gray-600 relative z-0">Carregando edital...</div>
        `;
        document.body.appendChild(sidebar);

        // Bind events manually
        document.getElementById('edital-close-btn').onclick = (e) => {
            e.stopPropagation();
            app.toggleEdital();
        };

        document.getElementById('edital-search').onkeyup = () => app.filterEdital();

        // 3. Close on click outside (Improved)
        document.addEventListener('click', (e) => {
            const sb = document.getElementById('edital-sidebar');
            const btn = document.getElementById('edital-toggle-btn');

            if (sb && sb.classList.contains('open')) {
                // If click is NOT on sidebar AND NOT on the toggle button
                if (!sb.contains(e.target) && !btn.contains(e.target)) {
                    app.toggleEdital();
                }
            }
        });

        // 4. Fetch Content
        try {
            const res = await fetch('data/edital.json');
            if (res.ok) {
                app.editalText = await res.json();
                app.renderEditalContent();
            } else {
                document.getElementById('edital-content').textContent = "Edital não encontrado (data/edital.json).";
            }
        } catch (e) {
            console.error("Erro edital", e);
        }
    },

    toggleEdital: () => {
        const sb = document.getElementById('edital-sidebar');
        sb.classList.toggle('open');
    },

    filterEdital: () => {
        const term = document.getElementById('edital-search').value.toLowerCase();
        if (term.length < 3) {
            app.renderEditalContent(); // Reset if empty
            return;
        }
        app.renderEditalContent(term);
    },

    renderEditalContent: (searchTerm = null) => {
        const container = document.getElementById('edital-content');
        let data = app.editalText;

        // If data is string (error/loading), just show it
        if (typeof data === 'string') {
            try {
                data = JSON.parse(data);
            } catch (e) {
                container.innerHTML = data;
                return;
            }
        }

        if (!data || !Array.isArray(data)) return;

        let html = '';
        let matchFound = false;

        data.forEach((section, index) => {
            let sectionMatches = false;
            let topicsHtml = '';

            // Filter Topics
            section.topics.forEach(topic => {
                let text = topic;
                let isMatch = false;

                if (searchTerm) {
                    const regex = new RegExp(`(${searchTerm})`, 'gi');
                    if (regex.test(text)) {
                        text = text.replace(regex, '<span class="edital-highlight">$1</span>');
                        isMatch = true;
                        sectionMatches = true;
                        matchFound = true;
                    }
                }

                if (!searchTerm || isMatch || sectionMatches) { // Show all if no search, or if match
                    // If searching, only show matching topics? Or show context?
                    // Let's show all topics if the SECTION matches, or specific topics if they match
                    // Better: If search exists, only show matching topics UNLESS the section title matched?
                    // User asked for "live search". Usually filtering out non-matches is best.
                }
            });

            // Re-logic for filtering:
            // 1. If no search, show everything.
            // 2. If search, show sections that have matches, and only the matching topics (or title matches).

            const titleMatches = searchTerm && new RegExp(searchTerm, 'gi').test(section.title);

            // Build Topics
            const topicsToRender = section.topics.map(t => {
                let text = t;
                let isMatch = false;
                if (searchTerm) {
                    const regex = new RegExp(`(${searchTerm})`, 'gi');
                    if (regex.test(text)) {
                        text = text.replace(regex, '<span class="edital-highlight">$1</span>');
                        isMatch = true;
                    }
                }
                return { text, isMatch };
            }).filter(item => !searchTerm || titleMatches || item.isMatch);

            if (topicsToRender.length > 0) {
                // Highlight title if needed
                let title = section.title;
                if (searchTerm && titleMatches) {
                    title = title.replace(new RegExp(`(${searchTerm})`, 'gi'), '<span class="edital-highlight">$1</span>');
                }

                html += `
                    <div class="edital-header flex justify-between items-center group cursor-default">
                        <span>${title}</span>
                        <button onclick="app.copyEditalSection(${index})" title="Copiar Tópicos" 
                            class="text-gray-400 hover:text-blue-600 opacity-0 group-hover:opacity-100 transition p-1">
                            <span class="material-icons text-sm">content_copy</span>
                        </button>
                    </div>`;
                topicsToRender.forEach(t => {
                    html += `<span class="edital-topic-number">${t.text}</span>`;
                });
            }
        });

        if (searchTerm && html === '') {
            html = '<div class="text-center p-4 text-gray-400">Nenhum resultado encontrado.</div>';
        }

        container.innerHTML = html;

        // Auto-scroll to first match
        if (searchTerm) {
            setTimeout(() => {
                const match = container.querySelector('.edital-highlight');
                if (match) match.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }, 100);
        }
    },

    copyEditalSection: (index) => {
        let data = app.editalText;
        if (typeof data === 'string') data = JSON.parse(data);

        const section = data[index];
        if (!section) return;

        const text = section.topics.join('\n');
        navigator.clipboard.writeText(text).then(() => {
            // Simple toast
            const toast = document.createElement('div');
            toast.className = 'fixed bottom-10 left-1/2 transform -translate-x-1/2 bg-gray-900 text-white px-4 py-2 rounded-full text-sm shadow-xl z-[9999] fade-in';
            toast.textContent = "Tópicos copiados!";
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 2000);
        }).catch(err => {
            console.error('Erro ao copiar:', err);
            alert('Erro ao copiar (permissão negada?)');
        });
    },

    loadQuestions: async () => {
        try {
            const res = await fetch(app.config.jsonPath);
            app.questions = await res.json();
            console.log(`Loaded ${app.questions.length} questions.`);
        } catch (e) {
            alert("Erro ao carregar questões: " + e.message);
        }
    },

    loadProgress: async () => {
        try {
            // Fetch stats from API
            const res = await fetch(`api/get_stats.php?user_name=${encodeURIComponent(app.currentUser)}`);
            const data = await res.json();
            if (data.success) {
                // Process stats if needed, or simply trust local storage for "Mistakes" 
                // For "Mistakes" mode, we need to know *which* questions were wrong.
                // The simple SQL backend stores 'is_correct'. 
                // We can fetch full history or maintain a local 'mistakes' list for offline-first speed.
                // For simplicity/robustness, let's use LocalStorage for the 'mistakes' list 
                // and SQL for the persistent 'score' tracking.

            }
        } catch (e) {
            console.error("Offline or API error", e);
        }

        // Load local mistakes/history for session generation
        const localHistory = JSON.parse(localStorage.getItem(`history_${app.config.appId}`)) || { answered: [], mistakes: [] };
        app.localHistory = localHistory;
    },

    updateMenuStats: () => {
        // Calculate stats from local history
        const answeredCount = app.localHistory.answered.length;
        const mistakesCount = app.localHistory.mistakes.length;
        // Total correct? We can estimate or track it.
        // Let's rely on the counts we have.

        document.getElementById('stats-total-answered').textContent = answeredCount;
        document.getElementById('count-mistakes').textContent = mistakesCount;

        // New questions count
        const newCount = app.questions.length - answeredCount;
        document.getElementById('count-new').textContent = Math.max(0, newCount);
    },

    showMenu: () => {
        document.getElementById('view-menu').classList.remove('hidden');
        document.getElementById('view-quiz').classList.add('hidden');
        document.getElementById('view-summary').classList.add('hidden');
        app.updateMenuStats();
    },

    startSession: (mode) => {
        app.lastMode = mode;
        app.currentSession = [];
        app.score = { correct: 0, wrong: 0, answered: 0 };
        app.currentIndex = 0;

        const allIds = app.questions.map(q => q.id);
        const answeredIds = new Set(app.localHistory.answered);
        const mistakeIds = new Set(app.localHistory.mistakes);

        if (mode === 'new') {
            // Filter unanswred
            app.currentSession = app.questions.filter(q => !answeredIds.has(q.id));
        } else if (mode === 'mistakes') {
            app.currentSession = app.questions.filter(q => mistakeIds.has(q.id));
        } else {
            // All / Shuffle
            app.currentSession = [...app.questions];
        }

        // Shuffle
        app.currentSession.sort(() => Math.random() - 0.5);

        // Limit to 50
        app.currentSession = app.currentSession.slice(0, 50);

        if (app.currentSession.length === 0) {
            alert("Nenhuma questão disponível para este modo!");
            return;
        }

        // UI Setup
        document.getElementById('view-menu').classList.add('hidden');
        document.getElementById('view-summary').classList.add('hidden');
        document.getElementById('view-quiz').classList.remove('hidden');

        app.renderQuestionsInternal();
        // Update Navbar
        app.updateNavbar();
    },

    renderQuestionsInternal: () => {
        const list = document.getElementById('questions-list');
        list.innerHTML = '';

        app.currentSession.forEach((q, index) => {
            const el = document.createElement('div');
            el.className = 'bg-white/90 backdrop-blur-sm p-6 rounded-xl shadow-lg border border-white/20 fade-in';
            el.innerHTML = `
                <div class="flex justify-between text-gray-400 text-xs mb-4 uppercase tracking-wider font-bold">
                    <span>Questão ${q.id}</span>
                    <span>${app.config.appName}</span>
                </div>
                <div class="text-gray-800 text-lg mb-6 leading-relaxed font-medium">
                    ${app.formatStatement(q.statement)}
                </div>
                <div class="space-y-3 options-container" id="q-${index}-options">
                    ${Object.entries(q.options).map(([key, text]) => `
                        <button onclick="app.checkAnswer(${index}, '${key}', this)" 
                            class="w-full text-left p-4 rounded-lg border-2 border-transparent bg-gray-50 hover:bg-blue-50 hover:border-blue-200 transition-all duration-200 group flex items-start gap-3">
                            <span class="w-8 h-8 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center font-bold text-sm group-hover:bg-blue-600 group-hover:text-white transition-colors">
                                ${key.toUpperCase()}
                            </span>
                            <span class="flex-1 pt-1 opacity-80 group-hover:opacity-100">${text}</span>
                        </button>
                    `).join('')}
                </div>
                <div id="q-${index}-feedback" class="hidden mt-4 p-4 rounded-lg text-sm font-bold"></div>
            `;
            list.appendChild(el);
        });
    },

    formatStatement: (lines) => {
        if (!lines || !lines.length) return '';
        return lines.reduce((acc, line, i) => {
            if (i === 0) return line;

            const prev = lines[i - 1].trim();
            const curr = line.trim();

            // Detection heuristics for breaks
            const isRoman = /^(I|II|III|IV|V|VI|VII|VIII|IX|X)\.?\s/.test(curr); // I. II. ...
            const isParen = /^\(\s*\)/.test(curr);      // ( )
            const isNumber = /^\d+\.\s/.test(curr);     // 1. 2.
            const prevEndsColon = prev.endsWith(':');   // Line ending in :

            if (isRoman || isParen || isNumber || prevEndsColon) {
                return acc + '<br><br>' + line;
            }
            return acc + ' ' + line;
        }, '');
    },

    checkAnswer: (index, selectedKey, btnElement) => {
        // Prevent re-answering
        if (btnElement.parentElement.classList.contains('answered')) return;

        const question = app.currentSession[index];
        const isCorrect = selectedKey.toLowerCase() === question.gabarito.toLowerCase();
        const container = document.getElementById(`q-${index}-options`);
        const feedback = document.getElementById(`q-${index}-feedback`);

        container.classList.add('answered');

        // Highlight logic
        const buttons = container.querySelectorAll('button');
        buttons.forEach(btn => {
            btn.disabled = true;
            btn.classList.add('opacity-50', 'cursor-not-allowed');

            // If this button is the correct answer
            const btnKey = btn.querySelector('span').innerText.trim().toLowerCase();
            if (btnKey === question.gabarito.toLowerCase()) {
                btn.classList.remove('bg-gray-50', 'hover:bg-blue-50', 'opacity-50');
                btn.classList.add('bg-green-100', 'border-green-500', 'text-green-900');
                btn.querySelector('span').classList.add('bg-green-600', 'text-white');
            }
            // If this button was the WRONG selection
            if (!isCorrect && btn === btnElement) {
                btn.classList.remove('bg-gray-50', 'hover:bg-blue-50', 'opacity-50');
                btn.classList.add('bg-red-100', 'border-red-500', 'text-red-900');
                btn.querySelector('span').classList.add('bg-red-600', 'text-white');
            }
        });

        // Feedback Text
        feedback.classList.remove('hidden');
        if (isCorrect) {
            feedback.classList.add('bg-green-50', 'text-green-700');
            feedback.textContent = "Excelente! Resposta Correta.";
            app.score.correct++;
        } else {
            feedback.classList.add('bg-red-50', 'text-red-700');
            feedback.textContent = `Atenção! A resposta correta é a letra ${question.gabarito.toUpperCase()}.`;
            app.score.wrong++;
        }
        app.score.answered++;
        app.updateNavbar();

        // Save Progress API
        app.saveProgressToAPI(question.id, isCorrect);

        // Update Local History
        app.updateLocalHistory(question.id, isCorrect);
    },

    saveProgressToAPI: (qId, isCorrect) => {
        fetch('api/save_progress.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                user_name: app.currentUser,
                app_id: app.config.appId,
                question_id: qId,
                is_correct: isCorrect
            })
        }).catch(err => console.error("API Save Error", err));
    },

    updateLocalHistory: (qId, isCorrect) => {
        if (!app.localHistory.answered.includes(qId)) {
            app.localHistory.answered.push(qId);
        }

        if (!isCorrect) {
            if (!app.localHistory.mistakes.includes(qId)) {
                app.localHistory.mistakes.push(qId);
            }
        } else {
            // Remove from mistakes if corrected
            const idx = app.localHistory.mistakes.indexOf(qId);
            if (idx > -1) {
                app.localHistory.mistakes.splice(idx, 1);
            }
        }

        localStorage.setItem(`history_${app.config.appId}`, JSON.stringify(app.localHistory));
    },

    updateNavbar: () => {
        const el = document.getElementById('navbar-score');
        el.textContent = `${app.score.correct} / ${app.currentSession.length}`;
    },

    finishSession: () => {
        document.getElementById('view-quiz').classList.add('hidden');
        document.getElementById('view-summary').classList.remove('hidden');

        document.getElementById('summary-correct').textContent = app.score.correct;
        document.getElementById('summary-wrong').textContent = app.score.wrong;

        // Recalc menu stats for next time
        app.updateMenuStats();

        window.scrollTo({ top: 0, behavior: 'smooth' });
    },


    // --- Notebook Generation ---
    showNotebookSetup: () => {
        document.getElementById('view-menu').classList.add('hidden');
        document.getElementById('view-quiz').classList.add('hidden');
        document.getElementById('view-summary').classList.add('hidden');
        document.getElementById('view-notebook-setup').classList.remove('hidden');
        document.getElementById('view-notebook').classList.add('hidden');
    },

    generateNotebook: () => {
        const input = document.getElementById('notebook-keywords').value;
        const keywords = input.split(',').map(k => k.trim()).filter(k => k.length > 0);

        let filtered = [];
        if (keywords.length === 0) {
            if (!confirm("Gerar caderno com TODAS as questões? Isso pode travar seu navegador.")) return;
            filtered = [...app.questions];
        } else {
            filtered = app.questions.filter(q => {
                // Check statement
                const text = (Array.isArray(q.statement) ? q.statement.join(' ') : q.statement).toLowerCase();
                return keywords.some(k => text.includes(k.toLowerCase()));
            });
        }

        if (filtered.length === 0) {
            alert("Nenhuma questão encontrada com essas palavras-chave.");
            return;
        }

        app.renderNotebook(filtered, keywords);
    },

    renderNotebook: (questions, keywords) => {
        const container = document.getElementById('notebook-content');
        const answersContainer = document.getElementById('notebook-answers');

        container.innerHTML = '';
        answersContainer.innerHTML = '';
        answersContainer.parentElement.classList.add('hidden'); // Hide the bottom key section

        // Header
        const date = new Date().toLocaleDateString('pt-BR');
        document.getElementById('notebook-subtitle').textContent = `Gerado em ${date} • ${questions.length} questões`;
        if (keywords.length > 0) {
            document.getElementById('notebook-title').textContent = `Caderno: ${keywords.join(', ')}`;
        } else {
            document.getElementById('notebook-title').textContent = `Caderno Completo`;
        }

        // Render Questions
        questions.forEach((q, index) => {
            const num = index + 1;
            const el = document.createElement('div');
            el.className = 'mb-10 break-inside-avoid border-b border-gray-100 pb-6'; // Added padding and border

            // Format statement (simplified version of formatStatement without extra breaks maybe?) 
            // Reuse app.formatStatement but ensure it looks good in print
            const statementHtml = app.formatStatement(q.statement);

            let optionsHtml = '';
            Object.entries(q.options).forEach(([key, text]) => {
                optionsHtml += `
                    <div class="flex gap-2 mb-1 pl-4">
                        <span class="font-bold text-gray-700">(${key.toUpperCase()})</span>
                        <span class="text-gray-800">${text}</span>
                    </div>
                `;
            });

            el.innerHTML = `
                <div class="font-bold text-gray-900 mb-2">Questão ${num} <span class="text-xs font-normal text-gray-500">(${q.id})</span></div>
                <div class="text-gray-800 text-justify mb-4 leading-snug text-sm">${statementHtml}</div>
                <div class="text-sm mb-4">${optionsHtml}</div>
                
                <!-- Answer Key Inline -->
                <div class="flex justify-end pt-2">
                    <div class="bg-gray-100 px-3 py-1 rounded text-xs font-mono font-bold text-gray-500 border border-gray-200">
                        Gabarito: ${q.gabarito.toUpperCase()}
                    </div>
                </div>
            `;
            container.appendChild(el);
        });

        // Show View
        document.getElementById('view-notebook-setup').classList.add('hidden');
        document.getElementById('view-notebook').classList.remove('hidden');
        window.scrollTo(0, 0);
    },

    resetHistory: () => {
        if (confirm("Tem certeza que deseja apagar todo o histórico deste módulo?")) {
            app.localHistory = { answered: [], mistakes: [] };
            localStorage.setItem(`history_${app.config.appId}`, JSON.stringify(app.localHistory));
            app.updateMenuStats();
            alert("Histórico apagado.");
        }
    }
};

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', app.init);

window.app = app;
